/**
 * 
 */
package com.ideazd.api.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import com.ideazd.api.model.Commodity;
import com.ideazd.api.model.CommodityCollect;
import com.ideazd.api.model.CommodityComment;
import com.ideazd.api.model.CommodityVersion;
import com.ideazd.api.model.CommodityVersionPic;
import com.ideazd.api.model.OrderDetails;
import com.ideazd.api.model.OrderSummary;
import com.ideazd.api.model.UserCommodityBrowse;
import com.ideazd.api.model.dto.RetDTO;
import com.ideazd.api.tools.SysUtil;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Page;

/**
 * @author yzz
 * @create 2016年5月16日 下午1:38:54
 */
@ControllerBind(controllerKey="comm")
public class CommodityController extends Controller {
	private static final Logger log = Logger.getLogger(CommodityController.class);
	
	/**
	 * 获取商品列表
	 */
	public void getCommodityList(){
		String commName = getPara("commodityName");
		String pageIndex = getPara("pageIndex");
		Map<Object, Object> ret = new HashMap<Object,Object>();
		
		if(StrKit.isBlank(pageIndex)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		
		String sql = "from sta_commodity where commodity_status = '0'";
		
		if(!StrKit.isBlank(commName)){
			sql += " and commodity_name like '%"+commName+"%'";
		}
		
		try {
			
			Page<Commodity> commodityPage = Commodity.dao.paginate(Integer.parseInt(pageIndex), Integer.parseInt(PropKit.get("firstLimit").toString()), "select * ", sql+" order by sort");
			List<Map<Object, Object>> commodityList = new ArrayList<Map<Object, Object>>();
			
			for(Commodity c : commodityPage.getList()){
				Map<Object, Object> commodity = new HashMap<Object,Object>();
				commodity.put("commodityId", c.get("id"));
				commodity.put("commodityName", c.get("commodity_name"));
				commodity.put("commodityPrice", c.get("commodity_price"));
				commodity.put("commodityPicture", PropKit.get("server_uri") + c.get("commodity_picture"));
				commodityList.add(commodity);
			}
			
			Map<Object, Object> data = new HashMap<Object,Object>();
			data.put("totalPage", commodityPage.getTotalPage());
			data.put("commodityList", commodityList);
			
			ret.put("code","0");
			ret.put("msg","成功");
			ret.put("data", data);
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
	}
	
	/**
	 * 获取商品详细
	 */
	@SuppressWarnings("null")
	public void getCommodityDetail(){
		String commodityId = getPara("commodityId");
		String useId = getPara("useId");
		Map<Object, Object> ret = new HashMap<Object,Object>();
		
		if(StrKit.isBlank(commodityId)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try {
			
			Commodity commodity = Commodity.dao.findById(commodityId);
			Map<Object, Object> data = new HashMap<Object,Object>();
			data.put("commodityId", commodity.get("id"));
			data.put("commodityName", commodity.get("commodity_name"));
			data.put("commodityTitle", commodity.get("commodity_title"));
			data.put("commodityPrice", commodity.get("commodity_price"));
			data.put("commodityPicture", PropKit.get("server_uri") +commodity.get("commodity_picture"));
			data.put("commodityDesc", commodity.get("commodity_desc_url"));
			//是否收藏
			boolean isCollect = false;
			
			if(!StrKit.isBlank(useId)){
				CommodityCollect collect = CommodityCollect.dao.findFirst("select * from sta_commodity_collect where useid = '"+useId+"' and commid = '"+commodityId+"'");
				
				if(null != collect){
					isCollect = true;
				}
			}
			
			data.put("isCollect", isCollect);
			
			
			List<CommodityVersion> commodityVersions = CommodityVersion.dao.find("select * from sta_commodity_version where commodity_id = '"+commodityId+"' order by version_sort desc");
			List<Map<Object, Object>> commodityVersionList = new ArrayList<Map<Object, Object>>();
			
			//商品型号
			for(CommodityVersion v:commodityVersions){
				Map<Object, Object> commodityVersion = new HashMap<Object,Object>();
				commodityVersion.put("versionId", v.get("id"));
				commodityVersion.put("versionName", v.get("version_type"));
				commodityVersion.put("versionPrice", v.get("version_price"));
				commodityVersion.put("versionStock", v.get("version_stock"));
				
				List<CommodityVersionPic> commodityVersionPics = CommodityVersionPic.dao.find("select * from sta_commodity_version_pic where version_id = '"+v.getStr("id")+"' order by pic_sort desc");
				List<Map<Object, Object>> commodityVersionPicList = new ArrayList<Map<Object, Object>>();
				
				//型号图片
				for(CommodityVersionPic p:commodityVersionPics){
					Map<Object, Object> commodityVersionPic = new HashMap<Object,Object>();
					commodityVersionPic.put("picUrl", PropKit.get("server_uri")+p.get("pic_url"));
					commodityVersionPicList.add(commodityVersionPic);
				}
				
				commodityVersion.put("versionPicList", commodityVersionPicList);
				
				commodityVersionList.add(commodityVersion);
				
			}
			data.put("commodityVersionList", commodityVersionList);
			
			//浏览记录
			
			if(!StrKit.isBlank(useId)){
				UserCommodityBrowse browse = UserCommodityBrowse.dao.findFirst("select * from sta_user_commodity_browse where comdetid = '"+commodityId+"' and useid = '"+useId+"'");
				
				if(null == browse){
					browse = new UserCommodityBrowse();
					browse.set("combroid", SysUtil.getUUID());
					browse.set("useid", useId);
					browse.set("comdetid", commodityId);
					browse.set("browsetime", new Date());
					browse.set("createtime", new Date());
					browse.save();
				}else{
					browse.set("browsetime", new Date());
					browse.update();
				}
			}
			
			
			ret.put("code","0");
			ret.put("msg","成功");
			ret.put("data", data);
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
		
	}
	
	/**
    * 获取订单列表
    */
   public void getOrderList(){
	   String useId = getPara("useId");
	   String pageIndex = getPara("pageIndex");
	   Map<Object,Object> ret = new HashMap<Object,Object>();
	   
	   if(StrKit.isBlank(useId)||StrKit.isBlank(pageIndex)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
	   
	   if(StrKit.isBlank(pageIndex)){
		   pageIndex = "1";
	   }
	   
	   try {
		   Map<Object, Object> data = new HashMap<Object,Object>();
			Page<OrderSummary> orderSummaryPage = OrderSummary.dao.paginate(Integer.parseInt(pageIndex), 10, "SELECT s.ordernumber,s.ordstate,s.`ordid`,s.commoditynumber,s.totalprice,s.`freight`,d.`commname`,d.`modprice`,d.`commpic`,d.commname", "  FROM sta_order_summary s LEFT JOIN  sta_order_details d ON s.`ordid` = d.`ordid` WHERE s.`useid` = '"+useId+"' GROUP BY d.ordid");
			List<Map<Object, Object>> orderSummaryList = new ArrayList<Map<Object, Object>>();
			
			for(OrderSummary o:orderSummaryPage.getList()){
				Map<Object, Object> order = new HashMap<Object,Object>();
				order.put("orderId", o.get("ordid"));
				order.put("orderNo", o.get("ordernumber"));
				order.put("commodityNumber", o.get("commoditynumber"));
				order.put("totalPrice", new BigDecimal(o.get("totalprice").toString()).add(new BigDecimal(o.get("freight").toString())));
				order.put("commodityPrice", o.get("modprice"));
				order.put("commodityName", o.get("commname"));
				order.put("orderStatus", o.get("ordstate"));
				order.put("commodityPicture", PropKit.get("server_uri") + o.get("commpic"));
				orderSummaryList.add(order);
			}
			
			data.put("totalPage", orderSummaryPage.getTotalPage());
			data.put("orderList", orderSummaryList);
			ret.put("data", data);
			ret.put("code","0");
			ret.put("msg","成功");
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
   }
   
   /**
    * 获取订单详情
    */
   public void getOrderDetail(){
	   String orderId = getPara("orderId");
       RetDTO ret = new RetDTO();
		
		try{
			Map<Object,Object> dataMap = new HashMap<Object,Object>();
			OrderSummary orderSummary = OrderSummary.dao.findById(orderId);
			dataMap.put("sendAddress", orderSummary.get("takeaddress"));
			dataMap.put("orderNo", orderSummary.get("ordernumber"));
			dataMap.put("zipCode", orderSummary.get("takezipcode"));
			dataMap.put("phone", orderSummary.get("takephone"));
			dataMap.put("receiver", orderSummary.get("takename"));
			dataMap.put("orderId", orderSummary.get("ordid"));
			dataMap.put("commodityTotalPrice", orderSummary.get("totalprice"));
			dataMap.put("freight", orderSummary.get("freight"));
			dataMap.put("distribution", orderSummary.get("distribution"));
			dataMap.put("orderStatus", orderSummary.get("ordstate"));
			dataMap.put("expressCompany", orderSummary.get("expresscompany"));
			dataMap.put("expressNumber", orderSummary.get("expressnumber"));
			dataMap.put("orderTotalPrice", new BigDecimal(orderSummary.get("totalprice").toString()).add(new BigDecimal(orderSummary.get("freight").toString())));
			
			
			List<OrderDetails> orderDetails = OrderDetails.dao.find("select * from sta_order_details where ordid = '"+orderId+"' order by buynumber desc");
			List<Map<Object,Object>> orderDetailList = new ArrayList<Map<Object,Object>>();
			
			for(OrderDetails order : orderDetails){
				Map<Object,Object> orderDetail = new HashMap<Object,Object>();
				orderDetail.put("orderDetailId", order.get("orddetid"));
				orderDetail.put("commodityId", order.get("commid"));
				orderDetail.put("commodityName", order.get("commname"));
				orderDetail.put("commodityPicture", PropKit.get("server_uri") + order.get("commpic"));
				orderDetail.put("versionId", order.get("modid"));
				orderDetail.put("versionName", order.get("modname"));
				orderDetail.put("versionPrice", order.get("modprice"));
				orderDetail.put("buyNum", order.get("buynumber"));
				orderDetail.put("isComment", SysUtil.getBoolean(order.get("iscomment").toString()));
				orderDetailList.add(orderDetail);
			}
			dataMap.put("orderDetailList", orderDetailList);
			ret.setCode("0");
			ret.setMsg("获取成功");
			ret.setData(dataMap);
			
			
			
				
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
   }
   
   /**
    * 收藏/取消收藏
    */
   @SuppressWarnings("null")
   public void setCollect(){
	   String useId = getPara("useId");
	   String commodityId = getPara("commodityId");
	   
	   RetDTO ret = new RetDTO();
	   
	   if(StrKit.isBlank(useId)||StrKit.isBlank(commodityId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try{
			CommodityCollect collect = CommodityCollect.dao.findFirst("select * from sta_commodity_collect where commid = '"+commodityId+"' and useid = '"+useId+"'");
			
			if(null != collect ){
				CommodityCollect.dao.deleteById(collect.get("id"));
			}else{
				collect = new CommodityCollect();
				collect.set("id", SysUtil.getUUID());
				collect.set("commid",commodityId );
				collect.set("useid",useId );
				collect.set("collectdate",new Date() );
				collect.set("createdate",new Date() );
				collect.save();
			}
			ret.setCode("0");
			ret.setMsg("成功");	
				
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
   }
   
   /**
    * 收藏商品接口
    */
   public void getCollectList(){
	   String useId = getPara("useId");
	   Map<Object,Object> ret = new HashMap<Object,Object>();
	   
	   if(StrKit.isBlank(useId)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
	   
	   try {
		   List<Commodity> commoditys = Commodity.dao.find("select c.* from sta_commodity c left join sta_commodity_collect cc on c.id = cc.commid where cc.useid = '"+useId+"' and c.commodity_status = '0'");
		   List<Map<Object,Object>> commodityList = new ArrayList<Map<Object,Object>>();
		   
		   for(Commodity c:commoditys){
			   Map<Object,Object> commodity = new HashMap<Object,Object>();
			   commodity.put("commodityId", c.get("id"));
			   commodity.put("commodityName", c.get("commodity_name"));
			   commodity.put("commodityPicture", PropKit.get("server_uri") + c.get("commodity_picture"));
			   commodity.put("commodityPrice", c.get("commodity_price"));
			   commodityList.add(commodity);
		   }
		   ret.put("data", commodityList);
		   ret.put("code","0");
		   ret.put("msg","成功");
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
   }
   
   /**
    * 评价商品
    */
   public void commentCommodity(){
	   String orderId = getPara("orderId");
	   String orderDetailId = getPara("orderDetailId");
	   String useId = getPara("useId");
	   String commodityId = getPara("commodityId");
	   String score = getPara("score");
	   String comContent = getPara("comContent");
	   RetDTO ret = new RetDTO();
	   
	   if(StrKit.isBlank(useId)||StrKit.isBlank(commodityId)||StrKit.isBlank(score)||StrKit.isBlank(comContent)||StrKit.isBlank(orderDetailId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try{
			
			CommodityComment commodityComment = new CommodityComment();
			commodityComment.set("comid", SysUtil.getUUID());
			commodityComment.set("useid", useId);
			commodityComment.set("orditalid", orderDetailId);
			commodityComment.set("comdetid",commodityId );
			commodityComment.set("score", score);
			commodityComment.set("comcontent", comContent);
			commodityComment.set("createtime", new Date());
			commodityComment.set("comstate", "0");
			
			if(commodityComment.save()){
				OrderDetails orderDetails = new OrderDetails();
				orderDetails.set("orddetid", orderDetailId);
				orderDetails.set("iscomment", "1");
				
				if(orderDetails.update()){
					OrderDetails commentStatus = OrderDetails.dao.findFirst("select count(*) as 'count' from sta_order_details where ordid = '"+orderId+"' and iscomment = '0'");
					
					System.out.println(commentStatus.get("count").toString());
					if(Integer.parseInt(commentStatus.get("count").toString()) == 0){
						OrderSummary orderSummary = new OrderSummary();
						orderSummary.set("ordid", orderId);
						orderSummary.set("ordstate", "04");
						orderSummary.set("updateid", useId);
						orderSummary.set("updatename", "接口评论完订单");
						orderSummary.set("updatedate", new Date());
						orderSummary.set("remarks", "完成订单");
						orderSummary.update();
					}
				}
			}
			
			
			
			ret.setCode("0");
			ret.setMsg("成功");	
				
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
   }
   
   /**
    * 获取商品评价列表
    */
   public void getCommodityComment(){
	   String commodityId = getPara("commodityId");
	   String pageIndex = getPara("pageIndex");
	   Map<Object,Object> ret = new HashMap<Object,Object>();
	   
	   if(StrKit.isBlank(commodityId)||StrKit.isBlank(pageIndex)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
	   
	   if(StrKit.isBlank(pageIndex)){
		   pageIndex = "1";
	   }
	   
	   try {
		    Map<Object, Object> data = new HashMap<Object,Object>();
			Page<CommodityComment> commodityCommentPage = CommodityComment.dao.paginate(Integer.parseInt(pageIndex), 10, "select c.*,u.gender,u.nickname,u.headportrait "," from sta_commodity_comment c left join sta_user u on u.useid = c.useid where comstate = '0' and comdetid = '"+commodityId+"'");
			List<Map<Object, Object>> commodityCommentList = new ArrayList<Map<Object, Object>>();
			
			for(CommodityComment c:commodityCommentPage.getList()){
				Map<Object, Object> commodityComment = new HashMap<Object,Object>();
				commodityComment.put("nickName", c.get("nickname"));
				commodityComment.put("headPortrait", c.get("headportrait"));
				//commodityComment.put("gender", c.get("gender"));
				commodityComment.put("score", c.get("score"));
				commodityComment.put("comContent", c.get("comcontent"));
				commodityComment.put("createTime", c.get("createtime"));
				commodityCommentList.add(commodityComment);
			}
			
			data.put("totalPage", commodityCommentPage.getTotalPage());
			data.put("commodityCommentList", commodityCommentList);
			ret.put("data", data);
			ret.put("code","0");
			ret.put("msg","成功");
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
   }
   
   public void refundCommodity(){
	   String orderId = getPara("orderId");
	   String refundReason = getPara("refundReason");
	   String useId = getPara("useId");
	   RetDTO ret = new RetDTO();
	   
	   if(StrKit.isBlank(useId)||StrKit.isBlank(orderId)||StrKit.isBlank(refundReason)||StrKit.isBlank(useId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try{
			OrderSummary orderSummary = new OrderSummary();
			orderSummary.set("ordid", orderId);
			orderSummary.set("refundreson", refundReason);
			orderSummary.set("ordstate", "05");
			orderSummary.set("updateid", useId);
			orderSummary.set("updatename", "接口用户退货");
			orderSummary.set("updatedate", new Date());
			orderSummary.set("remarks", "接口用户退货");
			orderSummary.update();
			ret.setCode("0");
			ret.setMsg("成功");	
				
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
   }
}
